import ProCard from '@ant-design/pro-card';
import { Slider } from 'antd';

const MS_PER_DAY = 1 * 24 * 60 * 60 * 1000;

const convertDate = (d) => {
  const arr = [];
  d.toLocaleDateString()
    .split('/')
    .forEach((e) => {
      if (e > 2021) {
        arr.push('2021');
      }
      if (e.length === 1) {
        arr.push(`0${e}`);
      } else {
        arr.push(e);
      }
    });
  return arr.join('-');
};

const TimeLine = ({ start, end, getRange }) => {
  const begin = new Date(start);
  const ends = new Date(end);
  const interval = Math.floor((ends - begin) / MS_PER_DAY);
  const marks = {
    0: start,
    [interval]: end,
  };
  const formatter = (value) => {
    const res = new Date(begin.getTime() + value * MS_PER_DAY).toLocaleDateString();
    return <span>{res}</span>;
  };
  const setRange = (value) => {
    const left = new Date(begin.getTime() + value[0] * MS_PER_DAY);
    const right = new Date(begin.getTime() + value[1] * MS_PER_DAY);
    getRange(convertDate(left), convertDate(right));
  };
  return (
    <ProCard style={{ width: '50%' }}>
      <Slider
        range
        defaultValue={[0, 200]}
        min={0}
        max={interval}
        marks={marks}
        tipFormatter={formatter}
        step={1}
        onChange={setRange}
      ></Slider>
    </ProCard>
  );
};

export default TimeLine;
